package aliyun

import (
	"fmt"
	"gitee.com/zhangyu520cw/cloud-station/store"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"os"
)

var (
	_ store.Uploader = &AliOssStore{}
)

func (o *Options) Validate() error {
	if o.EndPoint == "" || o.AccessKey == "" || o.AccessSecret == "" {
		return fmt.Errorf("endpoint,access_key secret i" +
			"s empty")
	}
	return nil
}
func NewDefaultAliOssStore() (*AliOssStore, error) {
	AccessKey := os.Getenv("ALI_AK")
	AccessSecret := os.Getenv("ALI_SK")
	OssEndpoint := os.Getenv("ALI_OSS_ENDPOINT")
	return NewAliOssStore(&Options{
		EndPoint:     OssEndpoint,
		AccessKey:    AccessKey,
		AccessSecret: AccessSecret,
	})
}
func NewAliOssStore(ops *Options) (*AliOssStore, error) {
	ops.Validate()
	c, err := oss.New(ops.EndPoint, ops.AccessKey, ops.AccessSecret)
	if err != nil {
		return nil, err
	}
	return &AliOssStore{
		client: c,
	}, nil
}

type AliOssStore struct {
	client *oss.Client
}

type Options struct {
	EndPoint     string
	AccessKey    string
	AccessSecret string
}

func (s *AliOssStore) Upload(bucketName string, objectKey string, fileName string) error {
	bucket, err := s.client.Bucket(bucketName)
	if err != nil {
		return err
	}
	//获取文件到bucket文件
	err = bucket.PutObjectFromFile(objectKey, fileName)
	if err != nil {
		return err
	}
	//4. 打印下载路径
	doloadURL, err := bucket.SignURL(objectKey, oss.HTTPGet, 60*60*24)
	if err != nil {
		return err
		return nil
	}
	fmt.Printf("文件下载URL: %s\n", doloadURL)
	fmt.Println("请在1天之内下载")
	return nil
}
